<template>
  <!-- 实测实量地图 -->
  <div class="mapBox">
    <div>
      <a-row :gutter="12" style="overflowx: auto">
        <!-- 实测实量地图左侧边栏：责任区域树；测量进度、测量点位列表根据状态显示其中一个 -->
        <MapSideBarLeft
          ref="mapSideBarLeft"
          :keys.sync="selectedKeys"
          :options.sync="selectOptions"
          :point.sync="activePoint"
          :loading="loading"
          :currentPoint="currentPoint"
          :pointList="pointList"
          :countVO="countVO"
          @handleSwitch="handleSwitch"
          @handleLoader="
            // 若是查看则请求点位名称列表
            isView && getPointTypes()
            search()
          "
          @submitForm="submitForm"
        />
        <!-- 实测实量地图点位操作区域 -->
        <MapContent
          ref="mapContent"
          :selectOptions.sync="selectOptions"
          :details.sync="detail"
          :points.sync="pointer"
          :point.sync="activePoint"
          :api="api"
          :datas="datas"
          :queryParams="queryParams"
          :loading="loading"
          :editModel="editModel"
          :pointList="pointList"
          :projectImg="projectImg"
          :selectedKeys="selectedKeys"
          @handleSearch="search"
          @handleManage="handleManage"
        />
        <!-- 实测实量地图右侧边栏：点位详情 -->
        <MapSideBarRight
          ref="mapSideBarRight"
          :api="api"
          :loading="loading"
          :datas="datas"
          :currentPoint="currentPoint"
          :pointList="pointList"
          :selectedKeys="selectedKeys"
          @handleSubmit="submitForm"
        />
      </a-row>
    </div>
  </div>
</template>

<script>
import MapSideBarLeft from '@/views/quality/measuredAmount/map/components/MapSideBarLeft.vue' // 实测实量地图左侧边栏
import MapContent from '@/views/quality/measuredAmount/map/components/MapContent.vue' // 实测实量地图点位操作区域
import MapSideBarRight from '@/views/quality/measuredAmount/map/components/MapSideBarRight.vue' // 实测实量地图右侧边栏
import { map } from '@/api/quality/reality' // 通用api
import BaseEditPage from '@/views/baseEditPage' // 通用编辑vue基础配置项
import Vue from 'vue'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    MapSideBarLeft,
    MapContent,
    MapSideBarRight
  },
  watch: {
    // 选中点位坐标变化切换选中点位
    detail: {
      immediate: true,
      handler(e) {
        this.$nextTick(() => {
          // 切换选中点位
          this.activePoint = [this.pointList.findIndex((item) => item.pointInfo.x === e.x && item.pointInfo.y === e.y)]
        })
      }
    },
    // 选中点位变化则重绘点位图
    currentPoint(e) {
      if (Object.keys(e)?.length && this.projectImg) {
        // 获取测量详情
        this.pointList.forEach((item) => {
          item.pointInfo.isActive = false
        })
        e.pointInfo.isActive = true
        this.$nextTick(() => {
          // 获取测量详情
          this.$refs.mapSideBarRight?.getMeasureInfo()
          // 滚轴滚到选中项
          this.$refs.mapSideBarLeft?.$refs.menuList &&
            (this.$refs.mapSideBarLeft.$refs.menuList.$el.scrollTop =
              this.$refs.mapSideBarLeft?.$refs[`menu_${this.activePoint?.[0]}`]?.[0].$el.offsetTop - 100)
          // 重绘点图
          this.$refs.point?.drawPoint()
        })
      }
    }
  },
  computed: {
    // 请求api
    api: () => map,
    // 选中点位对象
    currentPoint() {
      let active = this.pointList.find((item, index) => index === this.activePoint?.[0]) || {}
      return active
    },
    // 表格列表请求参数
    args() {
      let args = {}
      // 添加分部分项id
      if (this.selectOptions.id) {
        args.subItemId = this.selectOptions.id
      }
      return args
    }
  },
  data() {
    return {
      projectId: '', // 项目id
      isView: 0, // 是否为查看
      queryParams: {}, // 详情请求参数
      countVO: {}, // 测量进度
      activePoint: [], // 选中点位
      detail: {}, // 选中点位坐标对象
      loading: false, // 点位信息加载控件
      projectImg: '', // 施工图
      pointer: [], // 点位坐标列表
      editModel: '0', // 操作类型：0 添加 1 编辑 3 查看
      selectedKeys: [], // 选中节点
      form: null, // 弹窗参数
      datas: {}, // 点位列表
      pointList: [], // 点位坐标列表
      selectOptions: {}, // 选中节点对象
      token: '' // token
    }
  },
  mounted() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.$nextTick(() => {
      // 初始化区域
      this.$refs.mapSideBarLeft?.getDistrictList().then(() => {
        this.selectedKeys?.length && this.search()
      })
    })
  },
  methods: {
    /**
     * @description: 请求点位名称列表
     */
    getPointTypes() {
      // 节流
      if (this.loading) {
        return
      }
      this.$refs.mapContent?.getPointTypes()
      this.$refs.mapContent?.getQualityTypesLabel()
    },
    /**
     * 初始化点位
     */
    search() {
      // 节流
      if (this.loading) {
        this.$message.warning('正在加载中，请稍后再试！')
        return
      }
      // 重置选中点位
      
      this.activePoint = []
      this.loading = true
      map
        .postDetail({ isView:this.isView,respAreaNodeId: this.selectedKeys[0], ...this.queryParams })
        .then((res) => {
          if (res.code === 200) {
            this.$refs.mapContent && (this.$refs.mapContent.pointConfig = {})
            this.datas = res.data
            this.projectImg = res.data.fileInfo
              ? `/api/ycloud-file-center/oper/download?access_token=${this.token}&fileId=${res.data.fileInfo.fileId}`
              : '' // 区域施工图
            this.pointList = res.data.mapPoints // 点位列表
            this.countVO = res.data.countVO || {} // 测量进度
            this.pointList?.length && this.activePoint?.length === 0 && (this.activePoint = [0]) // 若无选中值则默认第一个选中
            this.pointer = this.pointList.length > 0
              ? this.pointList.map((item) =>
                  Object.assign(
                    item.pointInfo,
                    // 若是查看状态，则不同类型点位拥有不同颜色
                    {
                      actualType: item.actualType,
                      actualStatus: item.actualStatus,
                      mapId: item.mapId,
                      serialNumber: item.serialNumber,
                      title: item.name + item.pointName, // 点位表题
                    }
                  )
                )
              : [] // 点位坐标列表；添加颜色
              let that = this
              setTimeout(()=>{
                that.loading = false
              },1000)
          }
        })
        .catch((res) => {
          this.loading = false
        })
    },
    /**
     * 提交表单；form：编辑表单；e：编辑标识
     */
    submitForm(form, e) {
      let that = this
      let args = {
        projectId: that.projectId,
        subItemId: that.selectedKeys[0],
        points: e
          ? // 替换编辑内容
            that.pointList
              .map((item) => {
                if (item.mapId === form.mapId) {
                  item = form
                }
                return item
              })
              .filter((item) => (item.mapId ? true : false))
          : this.$clone(that.pointList)
      }
      // 遍历其他点位的设计值判空
      for (let index in args.points) {
        let item = args.points[index]
        item.serialNumber = Number(index) + 1
        item.checkItems.forEach((i) => {
          if ((i.judgmentTypeCode === '1' || i.judgmentTypeCode === '3') && !i.designVal && i.designVal != 0) {
            i.designVal = 0
          }
        })
      }
      that.datas.id && (args.id = that.datas.id) // 编辑则加id
      let editModel = args.id ? 1 : 0 // 编辑状态
      let name = ['create', 'update'][editModel] // 根据操作切换url地址
      that.$refs.mapSideBarRight.spinning = true
      e && (that.$refs.mapSideBarLeft.$refs.dialogForm.loading = true)
      // 提交表单
      map[name](args)
        .then((res) => {
          if (res.code === 200 || res.data.code === 200) {
            that.$refs.mapSideBarRight.spinning = false
            e && (that.$refs.mapSideBarLeft.$refs.dialogForm.loading = false)
            that.$message.success(['添加', '编辑'][editModel] + '点位成功！')
            that.$refs.mapContent && (that.$refs.mapContent.visible = false)
            e && (that.$refs.mapSideBarLeft.isEdit = false)
            that.search()
          }
        })
        .catch((res) => {
          that.$refs.mapSideBarRight.spinning = false
          e && (that.$refs.mapSideBarLeft.$refs.dialogForm.loading = false)
        })
    },
    /**
     * 停启用
     */
    handleSwitch() {
      let that = this
      let status = ['启用', '停用'][that.currentPoint.status] || '操作'
      that.$confirm({
        title: '温馨提示',
        content: `确认${status}？`,
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return map.switchStatus({ id: that.datas.id, mapId: that.currentPoint.mapId }).then((res) => {
            if (res.code === 200 || res.data.code == 200) {
              that.$message.success(status + '成功！')
              that.search()
            }
          })
        }
      })
    },
    /**
     * 点位：新增/编辑/查看
     */
    handleManage(e, a) {
      this.editModel = e
      this.$refs.mapContent.visible = true
    }
  }
}
</script>

<style lang="less" scoped>
.mapBox {
  min-width: 1300px;
  height: 100%;
  padding: 12px;
  overflow-y: hidden;
  width: 100%;
  background: #fff;
}
</style>